package BFS解决最短路径问题;

import java.util.LinkedList;
import java.util.Queue;

public class test1 {
    int[] dx = {0,0,1,-1};
    int[] dy = {1,-1,0,0};
    int n,m;
    boolean[][] flag = new boolean[101][101];
    public int nearestExit(char[][] maze, int[] entrance) {
        // 扩展了多少次,就是最少的步数
        n = maze.length;
        m = maze[0].length;
        int count = 0;

        Queue<int[]> queue = new LinkedList<>();
        queue.add(entrance);
        flag[entrance[0]][entrance[1]] = true;
        while (!queue.isEmpty()){
            count++;
            int size = queue.size();//因为要同时向外扩展一层,所以要全部拿出来
            for (int i = 0; i < size; i++) {
                int[] arr = queue.poll();
                int a = arr[0],b=arr[1];
                for (int j = 0; j < 4; j++) {
                    int x = a+dx[j];
                    int y = b+dy[j];
                    if(x>=0&&x<n&&y>=0&&y<m&&!flag[x][y]&&maze[x][y]=='.'){
                        // 判定是否为出口
                        if(x==0||x==n-1||y==0||y==m-1)return count;
                        queue.add(new int[]{x,y});
                        flag[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
}
